package io_nio;


import java.io.FileReader;
import java.io.IOException;
import java.io.PushbackReader;

/**
 * 推回缓冲区流
 * 实现：读取目标区的前面的内容
 * Created by butterfly on 2018/6/27.
 */
public class PushbackReaderDemo {
    public static void main(String[] args) {
        PushbackReader pr = null;
        try {
            pr = new PushbackReader(new FileReader("E:\\pp3\\effective-java\\src\\io_nio\\PushbackReaderDemo.java"), 64);
            char[] buf = new char[32];
            int hasRead = 0;
            String lastContent = "";//上次读取的内容
            while((hasRead = pr.read(buf))>0){
                String content = new String(buf, 0, hasRead);//把本次读到的字符转换成字符串
                int targetIndex = 0;//记录目标位置
                if((targetIndex = (lastContent+content).indexOf("new PushbackReader"))>0){
                    pr.unread((lastContent+content).toCharArray());//如果读到目标，把这次加上次的内容全部推回
                    char[] buf2 = new char[targetIndex];
                    pr.read(buf2,0,targetIndex);//读取指定长度放到字符数组
                    System.out.println("读到的目标内容是【"+new String(buf2,0,targetIndex)+"】");
                    System.exit(0);
                }else {
                    lastContent = content;
                    System.out.println("本次读取的内容是: "+content);
                    System.out.println("-------分割线--------");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (pr != null){
                    pr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
